package com.iarc.base

import android.app.Application
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner

/**
 * author:kanlulu
 * data  :6/30/21 11:44 PM
 **/
open class BaseApp : Application(), ViewModelStoreOwner {

    private lateinit var mAppViewModelStore: ViewModelStore
    private var mFactory: ViewModelProvider.Factory? = null

    companion object{
        lateinit var instance: BaseApp
    }

    override fun getViewModelStore() = mAppViewModelStore

    override fun onCreate() {
        super.onCreate()
        initNetRequestCommonParams()
        instance = this
        mAppViewModelStore = ViewModelStore()
    }

    /**
     * 添加公共请求头和参数
     */
    open fun initNetRequestCommonParams() {

    }

    /**
     * 获取一个全局的ViewModel
     */
    fun getAppViewModelProvider(): ViewModelProvider {
        return ViewModelProvider(this, this.getAppFactory())
    }

    private fun getAppFactory(): ViewModelProvider.Factory {
        if (mFactory == null) {
            mFactory = ViewModelProvider.AndroidViewModelFactory.getInstance(this)
        }
        return mFactory as ViewModelProvider.Factory
    }
}